<template>
    <div class="home" :style="{paddingTop:barHeight.allHeight+'px'}">
        <van-icon :style="{top: barHeight.allHeight - 30+'px'}" class="home_search" size="24px" name="search" @click="handleTo"/>
        <div class="home__swiper">
            <swiper class="swiper" :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval" :duration="duration">
                <swiper-item v-for="(item,index) in swiperList" :key="index">
                    <img :src="item.imgUrl" class="swiper-item"></img>
                </swiper-item>
            </swiper>
        </div>
        <div class="home__tabs">
            <div :class="['home__tabs-item', themeId === item.id ? 'active' : '']"
                 v-for="item in tabsList" :key="item.id"
                @click="handleChangeTab(item)">
                {{ item.name }}
            </div>
        </div>
        <div class="home__cards" :style="{ height: `calc(100vh - ${barHeight.allHeight + 220 + 46}px)` }">
            <scroll-view
                style="height: 100%"
                scroll-y="true"
                @scrolltolower="handleScrolltolower">
                <div class="home__cards-view">
                    <div class="home__cards-item" :style="{ marginRight: item.marginRight }" v-for="item in cardList" :key="item.id"
                         @click="handleCheckCard(item)">
                        <div class="img-box">
                            <img :style="{ width: item.width, height: item.height }" :src="item.coverUrl" alt="">
                        </div>
                        <p>{{ item.name }}</p>
                    </div>
                </div>
                <div style="text-align: center;line-height: 18px;margin-top: 10px;margin-bottom: 10px;color: rgba(31, 34, 45, 0.54);font-size: 14px">
                    {{ loadingText() }}
                </div>
            </scroll-view>

        </div>
        <van-tabbar
            :fixed="false"
            active="1"
            active-color="#07c160"
            inactive-color="#000"
            @change="onChangeTabBar"
        >
            <van-tabbar-item name="1" icon="home-o">首页</van-tabbar-item>
            <van-tabbar-item name="2" icon="add"></van-tabbar-item>
            <van-tabbar-item name="3" icon="friends-o">我的</van-tabbar-item>
        </van-tabbar>
    </div>
</template>

<script>
import { homeRequest, getUserInfo} from '../../../api'
import Interceptor from "@/utils/Interceptor";
// url参数解析
function getUrlkey(url) {
    var params = {};
    var urls = url.split("?");
    var arr = urls[1].split("&");
    for (var i = 0, l = arr.length; i < l; i++) {
        var a = arr[i].split("=");
        params[a[0]] = a[1];
    }
    return params;
}
export default {
    name: "tarbarHomeIndex",
    data() {
        return {
            // 轮播
            swiperList: [],
            indicatorDots: true,
            autoplay: true,
            interval: 2000,
            duration: 500,
            // tabs
            tabsList: [
            ],
            themeId: '',
            pageNo: 1,
            pageSize: 50,
            total: 0,
            cardList: [
            ],
            barHeight: {
                allHeight: 0
            },
        }
    },
    async onLoad(option) {
        if (option.q) {
            const params = getUrlkey(decodeURIComponent(option.q))
            wx.setStorageSync('shopId',params.shopId)
            wx.setStorageSync('shopName',params.shopName)
        }
        // // TODO 登陆验证手机号
        // if (!wx.getStorageSync('token')) {
        //     uni.redirectTo({
        //         url: '/pages/login/index'
        //     })
        //     return;
        // }
        var isTemp = {}
        const that = this
        uni.getSystemInfo({
            success(res) {
                let totalTopHeight = 88
                if (res.model.indexOf('iPhone X') !== -1) {
                    totalTopHeight = 88
                } else if (res.model.indexOf('iPhone') !== -1) {
                    totalTopHeight = 88
                }
                isTemp['statusBarHeight'] = res.statusBarHeight
                isTemp['titleBarHeight'] = totalTopHeight - res.statusBarHeight
                isTemp['allHeight'] = totalTopHeight
                that.barHeight = isTemp
            }
        })
    
        // TODO获取用户信息
        if(!wx.getStorageSync('userInfo') || !wx.getStorageSync('userInfo').phone) {
            const userInfoRes = await getUserInfo()
            wx.setStorageSync('userInfo', userInfoRes.data || {
                "authedAvatar": false,
                "avatar": "",
                "nickname": "",
                "phone": ""
            })
        }
        const swiperRes = await homeRequest.banner()
        this.swiperList = swiperRes.data
        const tabRes = await homeRequest.tabs()
        this.tabsList = tabRes.data
        if (tabRes.data.length) {
            this.handleChangeTab(tabRes.data[0])
        }
    },
    onShareAppMessage: function () {
    
    },
    methods: {
        handleTo() {
          uni.navigateTo({
              url: '/pages/tabBar/home/search'
          })
        },
        handleChangeTab(item) {
            this.themeId = item.id
            this.pageNo = 1
            this.cardList = []
            this.getPageList()
        },
        getPageList() {
            homeRequest.content({themeId: this.themeId, pageNo: this.pageNo, pageSize: this.pageSize }).then(res => {
                const systemInfo = wx.getStorageSync('systemInfo')
                const width = (systemInfo.screenWidth - 85) / 2
                const height = width * 1.48
                res.data = res.data.map((el,index) => {
                    return {
                        ...el,
                        width: width + 'px',
                        height: height + 'px',
                        marginRight: index % 2 === 0 ? '10px' : 0
                    }
                })
                this.cardList = [...this.cardList, ...res.data]
                this.total = res.data.total || 0
            })
        },
        //  滚动到底部触发加载更多数据
        handleScrolltolower() {
            let len = this.cardList.length
            if(len >= this.total) {
                return
            }
            this.pageNo += 1
            this.getPageList()
        },
        loadingText() {
            if (this.cardList.length < this.total) {
                return '加载中'
            } else {
                return  '没有更多数据了！'
            }
        },
        handleCheckCard(item) {
            uni.navigateTo({
                url: `/pages/myDetail/index2?id=${item.id}`,
            })
            // uni.navigateTo({
            //     url: `/pages/desgin/create?templateCardId=${item.id}&templateCardImageUrl=${item.coverUrl}&title=${item.name}`,
            // })
        },
        onChangeTabBar(value) {
            console.log(value.detail)
            
            if (value.detail == '2') {
                Interceptor().then(res => {
                    uni.navigateTo({
                        url: `/pages/desgin/create`
                    })
                })
            }
            if (value.detail == '3') {
                Interceptor().then(res => {
                    uni.redirectTo({
                        url: '/pages/tabBar/my/index'
                    })
                })
            }
        }
    }
}
</script>

<style lang="less">
.home {
    height: 100vh;
    padding: 16px 16px 0 16px;
    overflow: hidden;
    background-color: rgb(245,245,245) !important;
    display: flex;
    flex-direction: column;
    position: relative;
    .home_search {
        position: absolute;
    }
    &__swiper {
        width: 100%;
        height: 204px;
        margin-bottom: 16px;
        .swiper {
            height: 100%;
        }
        .swiper-item {
            width: 100%;
            height: 100%;
            background-color: #4cd964;
        }
    }
    &__tabs {
        display: flex;
        align-items: center;
        padding: 9px 0;
        &-item {
            width: 58px;
            height: 28px;
            border-radius: 14px;
            font-size: 16px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #303030;
            line-height: 28px;
            text-align: center;
            &.active {
                background: #00C65A;
                border-radius: 14px;
                color: #ffffff;
            }
        }
    }
    &__cards {
        overflow: hidden;
        width: 100%;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        &-view {
            display: flex;
            flex-wrap: wrap;
        }
        &-item {
            margin-top: 10px;
            margin-right: 5px;
            background-color: #FFFFFF;
            border-radius: 6px;
            overflow: hidden;
            padding: 10px;
            p {
                margin: 8px 0 0 8px;
                height: 20px;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #1F222D;
                line-height: 20px;
            }
        }
    }
}
</style>
